<?php

/*
 * $flow_id;流水线ID
 * $flow_name;l流水线名称
 * $departments;记录流水线的详细信息的二维数组（department_id,sort）
 */

include_once dirname(__FILE__) . '/Db.php';

class flow {

    public $flow_id;
    public $flow_name;
    public $departments; //array
    private $db;

    public function __construct() {
        $this->db = Db::get_instance();
    }

    //判断流水线是否存在
    public static function is_name_exit($flow_name) {
        $sql = "SELECT count(*) as num FROM fac_flow WHERE hidden='no' AND flow_name='" . $flow_name . "'";
        $rs = Db::get_instance()->query($sql);
        //   print_r($rs);
        $row = $rs[0];
        //   print_r($row);
        return $row["num"] > 0;
    }

    /**
     * 新增一个生产流程 
     * @param type $Name
     * @param type $departments
     * @return boolean
     */
    function insert($Name, $departments) {
        if (flow::is_name_exit($Name)) {
            return false;
        } else {
            $ret = $this->db->query("INSERT INTO fac_flow (flow_name) VALUES('$Name');");
            if ($departments == '') {
                return $ret;
            } else {
                return flow::save_department($ret, $departments);
            }
        }
    }

    public static function save_department($flow_id, $departments) {
        $Len = count($departments);
        if ($Len-- > 0) {
            Db::get_instance()->query("delete from fac_flow_mess where flow_id=" . $flow_id);
            $sql = "insert into fac_flow_mess (flow_id,department_id,is_last,is_firs,sort) values";
            foreach ($departments as $index => $department_item) {
                $is_firs = $index == 0 ? 1 : 0;
                $is_last = $index == $Len ? 1 : 0;
                $department_id = $department_item['department_id'];
                $sort = $department_item['sort'];
                $sql .= "($flow_id,$department_id,$is_last,$is_firs,$sort),";
            }
            $sql = substr($sql, 0, strlen($sql) - 1);
            return Db::get_instance()->query($sql);
        } else {
            return false;
        }
    }

//删除
    function delete($id) {
        return Util::dbDelete('fac_flow', 'flow_id', $id);
    }

//更新
    function update($Id, $Name) {
        if (flow::is_name_exit($Name)) {
            return false;
        } else {
            $update = "UPDATE fac_flow SET  flow_name='$Name' WHERE flow_id=$Id;";
            #echo $update;
            if ($this->db->query($update) > 0)
                return true;
            else
                return false;
        }
    }

    //查看
    function view($id = false) {
        if ($id) {
            return $this->db->query("select * from fac_flow WHERE hidden='no' AND flow_id=$id;");
        } else {
            return $this->db->query("select * from fac_flow WHERE hidden='no' ");
        }
    }

}
